package util;

import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * PackageName: util
 * ClassName: Hash
 * Author: tum0r
 * Time: 2020/5/23 16:23
 */
public class Hash {
    public static final String SHA256 = "sha-256";
    private static final String DefaultMode = SHA256;

    public String getHash(byte[] data, String mode) throws NoSuchAlgorithmException {
        StringBuilder result = new StringBuilder();
        if (data != null && data.length != 0) {
            MessageDigest digest = MessageDigest.getInstance(mode);
            data = digest.digest(data);
            String hex;
            for (byte temp : data) {
                hex = Integer.toHexString(temp & 0xff);
                if (hex.length() == 1) {
                    result.append("0");
                }
                result.append(hex);
            }
        }
        return result.toString().toUpperCase();
    }

    public String getHash(byte[] data) throws NoSuchAlgorithmException {
        return getHash(data, DefaultMode);
    }

    public String getHash(String text, String mode) throws NoSuchAlgorithmException {
        return getHash(text.getBytes(Charset.defaultCharset()), mode);
    }

    public String getHash(String text) throws NoSuchAlgorithmException {
        return getHash(text, DefaultMode);
    }
}
